package 删除链表的倒数第n个节点;

public class jishengjun {

    public static void main(String[] args) {
        //生成链表
        Node firstNode = new Node();
        firstNode.data = "1";
        Node currentNode = firstNode;
        for (int i = 1; i < 20; i++) {
            Node tempNode = new Node();
            tempNode.data = String.valueOf(i+1);
            currentNode.next = tempNode;
            currentNode = tempNode;
        }
        delete(firstNode, 8);
        currentNode = firstNode;
        //遍历打印node
        while (currentNode != null) {
            System.out.println(currentNode.data);
            currentNode = currentNode.next;
        }

    }

    /***
     * 删除倒数第N个node
     * @param firstNode
     * @param n
     */
    private static void delete(Node firstNode, int n) {
        if(n<=0){
            throw new IllegalArgumentException("要删除的数字无效");
        }
        Node currentNode = firstNode;
        int size = 0;
        //遍历node获取node size大小
        while (currentNode != null) {
            size++;
            currentNode = currentNode.next;
        }
        int resultIndex = size - n;
        currentNode = firstNode;
        while (resultIndex >= 0) {
            if (resultIndex == 1) {
                if (currentNode.next.next != null) {
                    currentNode.next = currentNode.next.next;
                } else {
                    currentNode.next = null;
                }
                break;
            }
            currentNode = currentNode.next;
            resultIndex--;
        }
    }

    static class Node {
        String data;
        Node next;
    }
}
